const mysql = require('mysql');
const config = require('./config')

const pool = mysql.createPool({
  ...config.dbConfig
})

let allServices = {
  query: function (sql, values) {
    return new Promise((resolve, reject) => {
      pool.getConnection(function (err, connection) {
        if (err) {
          reject(err)
        } else {
          connection.query(sql, values, (err, rows) => {
            if (err) {
              reject(err)
            } else {
              resolve(rows)
            }
            connection.release()
          })
        }
      })
    })
  },
  addClassify: (data) => {
    const _sql = `insert into classify(
      fKey,
      sKey,
      name
      ) VALUES (?,?,?) ON DUPLICATE KEY UPDATE name=name`
    return allServices.query(_sql, data)  
  },
  queryClassify: (arr) => {
    const _sql = `SELECT name FROM classify limit ?,?`
    return allServices.query(_sql, arr)
  },
  addDish: (data) => {
    const _sql = `insert into caipu(
      code,
      image,
      name,
      authorName,
      authorImage,
      score,
      describeTxt) values(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE code=code`
    return allServices.query(_sql, data)
  },
  addDishComplete: (data) => {
    const _sql = `insert into recipe(
      code,
      image,
      name,
      authorName,
      authorImage,
      score,
      describeTxt,
      n_pv,
      n_collects,
      n_dishes,
      ingredient,
      instruction
      ) values(?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE code=code`
    return allServices.query(_sql, data)
  },
  queryDish: (arr) => {
    const _sql = `SELECT name FROM classify limit ?,?`
    return allServices.query(_sql, arr)
  },
  addErrorLog: (data) => {
    const _sql = `insert into errLog(errmessage,extraData) values(?,?)`
    return allServices.query(_sql, data)
  },
  closePool: (msg) => {
    pool.end((err) => {
      console.log(msg, err)
    });
  }
}

module.exports = allServices;

// n_pv,
// n_collects,
// n_dishes,
// dish.stats.n_pv,
// dish.stats.n_collects,
// dish.stats.n_dishes,